-- 加锁器

local resty_lock = require('resty.lock')

local mis_log = nil
local mis_config = nil
local t_retCode = nil

--------------------------------------------------------------
local mis_lock = {
	s_name = string.match(debug.getinfo(1).short_src, '.*/(.*).lua');	-- 模块名称
}
local this = mis_lock

--------------------------------------------------------------
-- 说明：模块包含
-- 参数：模块表
this.modules_include = function(t_moddules)
	mis_log = t_moddules.mis_log
	mis_config = t_moddules.mis_config
	t_retCode = mis_config.t_retCode
end

--------------------------------------------------------------
-- 说明：加锁
-- 参数：s_name		锁名
-- 返回：n			状态码
--		ts 			描述
this.lock = function(s_name)
	local t_lock, s_desc = resty_lock:new('misLock', {exptime = 3})
	if not t_lock then
		s_desc = 'new lock failed, ' .. s_desc
		mis_log.error(s_desc)
		return t_retCode.n_SYS_ERR, s_desc
	end
	local n_elapsed
	n_elapsed, s_desc = t_lock:lock(s_name)
	if not n_elapsed then
		s_desc = 'lock failed, ' .. s_desc
		mis_log.error(s_desc)
		return t_retCode.n_SYS_ERR, s_desc
	end
	return t_retCode.n_OK, t_lock
end

--------------------------------------------------------------
-- 说明：解锁
-- 参数：t_lock		锁对象
-- 返回：n			状态码
--		s 			描述
this.unlock = function(t_lock)
	local b_ok, s_desc = t_lock:unlock()
	if not b_ok then
		s_desc = 'unlock failed, ' .. s_desc
		mis_log.error(s_desc)
		return t_retCode.n_SYS_ERR, s_desc
	end
	return t_retCode.n_OK
end

return this